//
//  ApiBase.m
//  OneCard
//
//  Created by sally on 16/2/17.
//  Copyright © 2016年 koalac. All rights reserved.
//

#import "ApiBase.h"
#import <AFNetworking/AFNetworking.h>

#define KEY_HOST @"Api_Host"
#define TIMEOUT 60

static ApiBase *_instance = nil;
static AFHTTPRequestOperationManager *_shareOperationManager = nil;

@implementation ApiBase

+ (ApiBase *)shareInstance {
  if (!_instance) {
    @synchronized(self) {
      if (!_instance) {
        _instance = [[self alloc] init];
      }
    }
  }
  return _instance;
}

- (void)setHost:(NSString *)host {
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  if (host != nil) {
    [defaults setObject:host forKey:KEY_HOST];
  } else {
    [defaults removeObjectForKey:KEY_HOST];
  }
  [defaults synchronize];
}

- (NSString *)host {
  NSString *host = [[NSUserDefaults standardUserDefaults] stringForKey:KEY_HOST];
  if (!host) {
    host = DEFAULT_API_HOST;
  }
  return host;
}

- (AFHTTPRequestOperationManager *)shareManager {
  if (!_shareOperationManager) {
    @synchronized(self) {
      if (!_shareOperationManager) {
        _shareOperationManager = [AFHTTPRequestOperationManager manager];
        AFHTTPRequestSerializer *requestSerializer = [[AFHTTPRequestSerializer alloc] init];
        _shareOperationManager.requestSerializer = requestSerializer;
        AFJSONResponseSerializer *responseSerializer = [[AFJSONResponseSerializer alloc] init];
        _shareOperationManager.responseSerializer = responseSerializer;
        _shareOperationManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
        // 超时设置
        _shareOperationManager.requestSerializer.timeoutInterval = TIMEOUT;
      }
    }
  }
  return _shareOperationManager;
}

@end
